<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Medium\Action\Sidebar\Group;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\App\Medium\Contract\MediumContract;
use MoChat\App\Medium\Contract\MediumGroupContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 批量创建、修改、删除.
 * @Controller
 */
class Set extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var MediumGroupContract
     */
    protected $mediumGroupService;

    /**
     * @Inject
     * @var MediumContract
     */
    protected $mediumService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/mediumGroup/set", methods="POST")
     */
    public function handle(): array
    {
        $user = user();

        // 参数验证
        $params = $this->request->all();
        $this->validated($params);

        // 处理参数
        [$storeData, $updateData, $deleteData] = $this->handleParam($user, $params);

        // 数据操作
        Db::beginTransaction();
        try {
            // 批量添加
            if (! empty($storeData)) {
                $this->mediumGroupService->createMediumGroups($storeData);
            }
            // 批量修改
            if (! empty($updateData)) {
                $this->mediumGroupService->updateMediumGroupByIds($updateData);
//                foreach ($updateData as $update){
//                    $this->mediumGroupService->updateMediumGroupById($updateData['id'],['name'=>$update['name'],'order'=>$updateData['order']]);
//                }
            }
            // 批量删除
            if (! empty($deleteData)) {
                $this->mediumGroupService->deleteMediumGroups($deleteData);
                foreach ($deleteData as $id) {
                    $this->mediumService->updateMediaByGroupId($id, ['medium_group_id' => 0]);
                }
            }

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '分组设置失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }

    /**
     * 处理参数.
     * @param array $user 用户信息
     * @param array $params 接受参数
     * @return array 响应数组
     */
    private function handleParam(array $user, array $params): array
    {
        // 基本信息
        $storeData = [];
        $updateData = [];
        $deleteData = [];
        $corpId = (int) $user['corpId'];
        $date = date('Y-m-d H:i:s');

        $count = $this->mediumGroupService->countMediumGroup($corpId);
        foreach ($params as $item) {
            if (empty($item['name'])) {
                throw new CommonException(ErrorCode::INVALID_PARAMS, '分组名称不能为空');
            }
            if (! isset($item['type'])) {
                continue;
            }
            // 添加
            if ($item['type'] === 1 || ! isset($item['id'])) {
                if (! empty($this->mediumGroupService->getMediumGroupsByCorpIdName($corpId, $item['name']))) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '分组名称已存在');
                }
                ++$count;
                $storeData[] = ['name' => $item['name'], 'order' => $count, 'corp_id' => $corpId, 'created_at' => $date];
            }
            // 修改
            if ($item['type'] === 2 && isset($item['id'])) {
                if (! empty($this->mediumGroupService->existMediumGroupByCorpIdName($corpId, $item['name'], $item['id']))) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '分组名称已存在');
                }
                $updateData[] = ['id' => $item['id'], 'name' => $item['name'], 'order' => $item['order']];
            }
            // 删除
            if ($item['type'] === 3) {
                $deleteData[] = $item['id'];
            }
        }
        return [
            $storeData, $updateData, $deleteData,
        ];
    }
}
